package com.back.end.Controller.App;

import com.back.end.Modal.Address;
import com.back.end.Modal.User;
import com.back.end.Service.AppUserService;
import com.back.end.utils.token.JwtUtil;
import com.back.end.utils.redis.RedisUtil;
import com.back.end.vo.Result;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;


@RestController
@RequestMapping("/App/user")
public class AppUserController {
    @Resource
    AppUserService appUserService;

    @Resource
    private RedisUtil redisUtil;


    @RequestMapping("/sendSms")
    public Result sendSms(String phone, String code) throws TencentCloudSDKException {
        appUserService.sendSms(phone, code);
        return Result.success("验证码发送成功");
    }

    @RequestMapping("/smsLogin")
    public Result smsLogin(String phone, String code, String name, String profile) {
        User user = appUserService.smsLogin(phone, code, name, profile);
        String userId = UUID.randomUUID().toString();
        Map<String, Object> info = new HashMap<>();
        info.put("phone", phone);
        info.put("code", code);
        String token = JwtUtil.sign(userId, info);
        redisUtil.set("accessToken", token, 60 * 24 * 30);
        return Result.loginSuccess(user, token);
    }

    @RequestMapping("/addAddress")
    public Result addAddress(@RequestBody Address address) {
        Address userAddress = new Address();
        userAddress.setName(address.getName());
        userAddress.setPhone(address.getPhone());
        userAddress.setAddress(address.getAddress());
        userAddress.setCustomerId(address.getCustomerId());
        appUserService.addAddress(userAddress);
        return Result.success("成功");
    }

    @RequestMapping("/getAddressList")
    public Result getAddressList(int customerId) {
        List addressList = appUserService.getAddressList(customerId);
        return Result.success(addressList);
    }

    @RequestMapping("/updateAddress")
    public Result updateAddress(@RequestBody Address address) {
        appUserService.updateAddress(address);
        return Result.success("成功");
    }

    @RequestMapping("/checkUserInfo")
    public Result checkUserInfo(String phone) {
        User u = appUserService.checkUserInfo(phone);
        return Result.success(u);
    }
}
